package com.camtc.camcenter.security;

import com.camtc.camcenter.config.jwt.JwtUserDetails;
import com.camtc.camcenter.dao.entity.CloudUser;
import com.camtc.camcenter.service.CloudUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义用户登录认证信息查询
 *
 * @author
 * @date
 */

@Service
public class CloudUserDetailsServiceImpl implements UserDetailsService {

    private CloudUserService cloudUserService;

    @Autowired
    public void setCloudUserService(CloudUserService cloudUserService) {
        this.cloudUserService = cloudUserService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        CloudUser user = cloudUserService.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 用户权限列表，根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比，决定是否可以调用接口
        List<String> roleStrs = cloudUserService.findPermissions(user.getUserName());
        List<GrantedAuthority> grantedAuthorities = roleStrs.stream().map(MyGrantedAuthority::new).collect(Collectors.toList());
        return new JwtUserDetails(username, user.getPassWord(), grantedAuthorities);
    }
}
